import {
  LockOutlined,
  UserOutlined,
} from '@ant-design/icons';
import {
  LoginFormPage,
  ProConfigProvider,
  ProFormText,
} from '@ant-design/pro-components';
import { Button, Tabs, message, theme, App } from 'antd';
import { history, Helmet } from '@umijs/max';
import { flushSync } from 'react-dom';
import React, { useState } from 'react';
import Settings from '../../../../config/defaultSettings';
import { userLogin } from '@/services/swagger/userController';
import { useModel } from '@umijs/max';

const Login = () => {
  const { token } = theme.useToken();
  const { message: msg } = App.useApp();
  const { initialState, setInitialState } = useModel('@@initialState');
  const [, setUserLoginState] = useState<API.UserVo>({});

  // 获取用户信息并更新全局状态
  const fetchUserInfo = async () => {
    const userInfo = await initialState?.fetchUserInfo?.();
    if (userInfo) {
      flushSync(() => {
        setInitialState((s) => ({
          ...s,
          currentUser: userInfo,
        }));
      });
    }
  };

  // 登录提交逻辑（保持不变）
  const handleSubmit = async (values: API.UserLoginRequest) => {
    try {
      const data = await userLogin(values);
      if (data.code === 0) {
        msg.success('登录成功！');
        await fetchUserInfo();
        const urlParams = new URL(window.location.href).searchParams;
        const redirect = urlParams.get('redirect') || '/';
        history.push(redirect);
        return;
      } else {
        msg.error('登录失败: ' + data.message);
      }
      if (data.data != null) {
        setUserLoginState(data.data.userVo);
      }
    } catch (error) {
      msg.error('登录失败，请重试！');
    }
  };

  return (
    <div style={{ backgroundColor: 'white', height: '100vh' }}>
      <Helmet>
        <title>登录 - {Settings.title}</title>
      </Helmet>
      <LoginFormPage
        onFinish={async (val: API.UserLoginRequest) => {
          await handleSubmit(val)
        }}
        logo="https://github.githubassets.com/favicons/favicon.png"
        backgroundVideoUrl="https://gw.alipayobjects.com/v/huamei_gcee1x/afts/video/jXRBRK_VAwoAAAAAAAAAAAAAK4eUAQBr"
        title="面试鸡-模拟面试平台"
        subTitle="账户密码登录"
        containerStyle={{
          backgroundColor: 'rgba(0, 0, 0, 0.65)',
          backdropFilter: 'blur(4px)',
        }}
        activityConfig={{
          style: {
            boxShadow: '0px 0px 8px rgba(0, 0, 0, 0.2)',
            color: token.colorTextHeading,
            borderRadius: 8,
            backgroundColor: 'rgba(255,255,255,0.25)',
            backdropFilter: 'blur(4px)',
          },
          title: '面试鸡-模拟面试平台',
          action: (
            <Button
              size="large"
              style={{
                borderRadius: 20,
                background: token.colorBgElevated,
                color: token.colorPrimary,
                width: 120,
              }}
              onClick={() => history.push('/user/register')}
            >
              去注册
            </Button>
          ),
        }}
      >
        <Tabs centered activeKey="account">
          <Tabs.TabPane key="account" tab="账户密码登录" />
        </Tabs>

        <ProFormText
          name="userAccount"
          fieldProps={{
            size: 'large',
            prefix: (
              <UserOutlined
                style={{ color: token.colorText }}
                className="prefixIcon"
              />
            ),
          }}
          placeholder="用户名: admin or user"
          rules={[{ required: true, message: '请输入用户名!' }]}
        />

        <ProFormText.Password
          name="userPassword"
          fieldProps={{
            size: 'large',
            prefix: (
              <LockOutlined
                style={{ color: token.colorText }}
                className="prefixIcon"
              />
            ),
          }}
          placeholder="密码: ant.design"
          rules={[{ required: true, message: '请输入密码！' }]}
        />

        <div style={{ marginBlockEnd: 24 }}>
          <a
            style={{ float: 'right' }}
            onClick={() => history.push('/user/register')}
          >
            没有账号？去注册
          </a>
        </div>
      </LoginFormPage>
    </div>
  );
};

// 包裹 ProConfigProvider 以启用暗色主题（可选）
export default () => {
  return (
    <ProConfigProvider dark>
      <Login />
    </ProConfigProvider>
  );
};
